package cn.congine.wizarpos.mall.dao.hibernate;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import cn.congine.wizarpos.mall.dao.MrtWechartUserInfoDao;
import cn.congine.wizarpos.mall.model.MrtWechartUserInfo;
import cn.congine.wizarpos.mall.utils.Function;

@Repository("mrtWechartUserInfoDao")
public class MrtWechartUserInfoDaoHibernate extends
		GenericDaoHibernate<MrtWechartUserInfo> implements
		MrtWechartUserInfoDao {

	public MrtWechartUserInfoDaoHibernate() {
		super(MrtWechartUserInfo.class);
	}

	@Override
	public MrtWechartUserInfo get(String openId, String mid) {
		Query query = getSession()
				.createQuery(
						"from MrtWechartUserInfo where openId=:openId and mid=:mid")
				.setParameter("mid", mid).setParameter("openId", openId);
		return (MrtWechartUserInfo) query.uniqueResult();
	}

	@Override
	public MrtWechartUserInfo save(MrtWechartUserInfo obj) {
		String uuid = Function.getUid();
		obj.setId(uuid);
		String sql = "INSERT INTO mrt_wechart_user_info (id, open_id, subscribe, nickname, "
				+ "sex, city, country, province, LANGUAGE, headimgurl, subscribe_time, mid)"
				+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createSQLQuery(sql);
		q.setString(0, uuid);
		q.setString(1, obj.getOpenId());
		q.setString(2, obj.getSubscribe());
		q.setString(3, obj.getNickname());
		q.setString(4, obj.getSex());
		q.setString(5, obj.getCity());
		q.setString(6, obj.getCountry());
		q.setString(7, obj.getProvince());
		q.setString(8, obj.getLanguage());
		q.setString(9, obj.getHeadimgurl());
		q.setString(10, obj.getSubscribeTime());
		q.setString(11, obj.getMid());
		q.executeUpdate();

		return obj;
	}

	@Override
	public void update(MrtWechartUserInfo obj) {
		String sql = "UPDATE mrt_wechart_user_info SET subscribe = ?, subscribe_time = ? WHERE id = ? and mid = ?";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createSQLQuery(sql);

		q.setString(0, obj.getSubscribe());
		q.setString(1, obj.getSubscribeTime());
		q.setString(2, obj.getId());
		q.setString(3, obj.getMid());
		q.executeUpdate();
	}

	@Override
	public MrtWechartUserInfo find(String id, String mid) {
		return (MrtWechartUserInfo) getSession()
				.createQuery(
						"from MrtWechartUserInfo where mid=:mid and id=:id")
				.setString("mid", mid).setString("id", id).uniqueResult();
	}

}
